package com.spring.oaassist.web.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.oa.api.web.dao.OaMapper;
import com.spring.common.web.dao.TracelogboMapper;
import com.spring.common.web.model.TracelogboWithBLOBs;
import com.spring.oaassist.web.dao.ReportMapper;
import com.spring.oaassist.web.model.BusinessDaily;
import com.spring.oaassist.web.model.CoursePlan;
import com.spring.oaassist.web.model.Custom;
import com.spring.oaassist.web.model.SalePlan;
import com.spring.oaassist.web.requestModel.RequestUser;
import com.spring.oaassist.web.service.ReportService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.security.web.model.User;
import com.spring.tools.MyTools;
import com.spring.tools.SpUtil;
import com.sso.api.web.dao.SsoMapper;
import com.sso.api.web.model.Family;
//import com.sso.api.web.model.Users;

@Service
public class ReportServiceImpl implements ReportService{
	@Resource
	private ReportMapper reprotMapper;
    @Resource
	private OaMapper oaMapper;
    @Resource
	private SsoMapper ssoMapper;
    @Resource
	private JedisCache jedisCache;    
    @Resource
	private TracelogboMapper tracelogboMapper;    

	@Override
	public List<CoursePlan> coursePlan(HashMap<String, Object> parm) {
		// TODO Auto-generated method stub
		return reprotMapper.coursePlan(parm);
	}

	
	@Override
	public List<SalePlan> salePlan(HashMap<String, Object> hm) {
		// TODO Auto-generated method stub
		return reprotMapper.salePlan(hm);
	}

	/**
	 * 营业日报表
	 */
	@Override
	public List<BusinessDaily> businessDaily(HashMap hm) {
		// TODO Auto-generated method stub
		return reprotMapper.businessDaily(hm);
	}
	
	@Override
	public List<Map<String, Object>> queryUserByDeptId(String dept_id,String shopDeptId,String priv_id) {
		Map<String,Object> sp = new HashMap<String,Object>();
		if(ApplicationUtils.isNotNull(dept_id)){
			sp.put("dept_id", dept_id);
			return oaMapper.queryUserByDeptId(sp);
		}else if(ApplicationUtils.isNotNull(shopDeptId)&&ApplicationUtils.isNotNull(priv_id)){
			sp.put("dept_id", shopDeptId);
			sp.put("dept_name_py", priv_id);
			/**
			 * 查询所有子部门
			 */
			List<Map<String,Object>> rl = oaMapper.queryDepartmentPark2(sp);
			List<Map<String,Object>> retl = new ArrayList<Map<String,Object>>();
			for(Map<String,Object> m:rl){
				retl.add(m);
			}
			queryAllDeptByParentList(retl,rl);
			String deptIDs = "";
			for(Map<String,Object> retm:retl){
				deptIDs+=ApplicationUtils.Object2String(retm.get("id"))+",";
			}
			if(ApplicationUtils.isNotNull(deptIDs)){
				sp.put("dept_id", deptIDs.substring(0,deptIDs.length()-1));
			}
			
			return oaMapper.queryUserByDeptId(sp);
		}else{
			return new ArrayList<Map<String,Object>>();
		}
	}
	
	/**
	 * 递归子部门
	 * @param rl
	 * @param parml
	 */
	private void queryAllDeptByParentList(List<Map<String,Object>> rl,
				List<Map<String,Object>> parml){
		List<Map<String,Object>> parmN = new ArrayList<Map<String,Object>>();
		if(parml!=null&&parml.size()>0){
			Map<String,Object> pm = new HashMap<String,Object>();
			for(Map<String,Object> model:parml){
				pm.put("dept_id", model.get("id"));
				List<Map<String,Object>> nl = oaMapper.queryDepartmentParkChildrenAll(pm);
				for(Map<String,Object> nm:nl){
					parmN.add(nm);
					rl.add(nm);
				}
			}
			queryAllDeptByParentList(rl,parmN);
		}
		
	}
	
	@Override
	public void insertCustomAssist(String note,String customAssistID,String customAssistName,String UserList,String InitialOperatorID,
			String InitialOperatorName,HttpServletRequest request) throws Exception{	
		HashMap<String,Object> parm=new HashMap<String,Object>();
		parm.put("note",note);
    	parm.put("customAssistID",customAssistID);
    	parm.put("customAssistName",customAssistName);
    	
    	parm.put("InitialOperatorID",InitialOperatorID);
    	parm.put("InitialOperatorName",InitialOperatorName);
    	//JSONArray json=new JSONArray(UserList);
    	JSONArray json = JSONArray.fromObject(UserList);
		
		for (int i = 0; i < json.size(); i++) {
			JSONObject jsonObject = json.getJSONObject(i);   	
			String cUserID=String.valueOf(jsonObject.get("c_user_id"));
			String phone=String.valueOf(jsonObject.get("phone"));
			String user_name=String.valueOf(jsonObject.get("user_name"));
			String roleID=String.valueOf(jsonObject.get("roleID"));
			String real_name=String.valueOf(jsonObject.get("real_name"));
			parm.put("cUserID", cUserID);
			parm.put("phone", phone);
			parm.put("user_name", user_name);
			parm.put("roleID", roleID);
			parm.put("userName", real_name);
			int count=reprotMapper.checkCustomAssistCount(parm);
			if(count>0){
				int effect=reprotMapper.updateCustomAssist(parm);
				
				TracelogboWithBLOBs tl = MyTools.getOaLogByRequest(request);
				tl.setEntitytypename("crm_customer_assist");
				tl.setEntityid(cUserID);
				tl.setLogcategory(2);
				tl.setLogdescription(MyTools.getChangeByMap(parm, "修改"));
				int effect2=tracelogboMapper.insert(tl);
				System.out.println(effect2);
			}else{
				int effect=reprotMapper.insertCustomAssist(parm);
				
				TracelogboWithBLOBs tl = MyTools.getOaLogByRequest(request);
				tl.setEntitytypename("crm_customer_assist");
				tl.setEntityid(cUserID);
				tl.setLogcategory(1);
				tl.setLogdescription(MyTools.getChangeByMap(parm, "新增"));
				int effect2=tracelogboMapper.insert(tl);
				System.out.println(effect2);
			}
		}
	}
	
	@Override
	public List<Family>  getUserByPhone(HashMap parm){
		return null;
		//return ssoMapper.getUserByPhone(parm);
	};
	
	@Override
	public List<Custom> getCustomList(String birthday,String customID,String admission_way_code,String parent_phone,String family_name,
    		String baby_phone,String real_name,String t_user_id) {
		HashMap<String,Object> parm=new HashMap(); 
		//return oaAssistMapper.getCustomList(parm);
		
		
		List<Custom> list=new ArrayList<Custom>();
//		 if(phone!=null&&!phone.equals("")){
//			 
//	        	parm.put("phone",phone);
//	        	
//	        }
		parm.put("birthday",birthday);
		parm.put("customID",customID);
		parm.put("admission_way_code",admission_way_code);
		
		parm.put("parent_phone",parent_phone);
		parm.put("family_name",family_name);
		parm.put("baby_phone",baby_phone);
		parm.put("real_name",real_name);
		parm.put("t_user_id",t_user_id);
		
		 
		
		 if(customID!=null&&!customID.equals("")){
				String[] idList = reprotMapper.getUserIDByAssistID(customID);
				HashMap<String,Object> hm4=new HashMap<String,Object>();		
				hm4.put("userList", idList);
				if(idList.length>0){
					list=ssoMapper.getUserListByIDs(hm4);
				}else{
					return list;
				}
	 		   
		 }else{			 
			 list= ssoMapper.getUserList(parm);	
			
		 }

		  System.out.println(parm.toString());

          
	        String[] cUserIDList=new String[list.size()] ;
	        
	        for(int i=0;i<list.size();i++){
	        	Custom custom=list.get(i);
	        	cUserIDList[i]= custom.getC_user_id();	        		        	
	        }
	        
	        List<Custom> list2=null;
	        
	        parm.put("list", cUserIDList);
	        if(cUserIDList.length!=0){
	        	list2=reprotMapper.getAssistListByUserID(parm);
	        }  
	        
	     //   HashMap<String, Object> p2 = new HashMap<String, Object>();
	       // p2.put("list", cUserIDList);
	        
	        //List<Users> list2 =oaAssistService.getUserByIDs(p2);
	        
	        
	        
	        for(Custom custom:list){
	        	for(Custom assist:list2){
	        		if(custom.getC_user_id().equals(assist.getC_user_id())){
	        			//custom.get users.getC_user_id()=
	        			custom.setAssistantName(assist.getAssistantName());
	        			custom.setAssistantID(assist.getAssistantID());
	        			custom.setNote(assist.getNote());
	        			custom.setChangedTime(assist.getChangedTime());
	        			custom.setOperatorID(assist.getOperatorID());
	        			custom.setOperatorName(assist.getOperatorName());
	        		}
	        	}
	        }

		return list;
	}
	

	@Override
	public List<HashMap<String,Object>> userList(HashMap<String,Object> hm) throws Exception{
		// TODO Auto-generated method stub
		//HashMap hm=new HashMap();
		return ssoMapper.getUserDetailList(hm);
		//return reprotMapper.userList(hm);
	}
	

	
	@Override
	public List<HashMap<String,Object>> getOrderList(String cUserID) throws Exception{
		// TODO Auto-generated method stub
		//HashMap hm=new HashMap();
		HashMap hm=new HashMap();
		hm.put("cUserID", cUserID);
		
		
		return reprotMapper.getOrderList(hm);
		//return reprotMapper.userList(hm);
	}
	

	
	@Override
	public List<HashMap<String,Object>> getOrderDetailList(String orderID) throws Exception{
		// TODO Auto-generated method stub
		//HashMap hm=new HashMap();
		HashMap hm=new HashMap();
		hm.put("orderID", orderID);
		return reprotMapper.getOrderDetailList(hm);
		//return reprotMapper.userList(hm);
	}
	
	@Override
	public List<HashMap<String,Object>> getCommonUserList(HashMap<String ,Object> hm) throws Exception{
		// TODO Auto-generated method stub
		//HashMap hm=new HashMap();
	//	HashMap hm=new HashMap();

		return ssoMapper.getCommonUserList(hm);
		//return reprotMapper.userList(hm);
	}
	
	
	
	@Override
	public List<HashMap<String,Object>> getParkList() throws Exception{
		// TODO Auto-generated method stub
		//HashMap hm=new HashMap();
		HashMap hm=new HashMap();
		return reprotMapper.getParkList(hm);

	}
	
	
	
	@Override
	public Map<String, Object> updateUserPark(String kids_park_id,String UserList) throws Exception {
		Map<String, Object> m = new HashMap<String, Object>();
	//	Map<String, Object> parm = new HashMap<String, Object>();


		HashMap hmc = MyTools.checkIsNotNull(kids_park_id, UserList);
		if (ApplicationUtils.isNotNull(hmc)) {
			return hmc;
		}

		String uuid = ApplicationUtils.randomUUID();

		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("kids_park_id", kids_park_id);
		
		
		
		
		JSONArray json = JSONArray.fromObject(UserList);
		
		String[] userList=new String[json.size()]; 
		
		for (int i = 0; i < json.size(); i++) {
			JSONObject jsonObject = json.getJSONObject(i);   	
			String c_user_id=String.valueOf(jsonObject.get("c_user_id"));		
			//parm.put("c_user_id", c_user_id);		
			userList[i]=c_user_id;
		}
		
		hm.put("userList", userList);
		
		int effect=ssoMapper.updateUserPark(hm);
		

		if (effect > 0) {

			m.put(ApplicationUtils.STATUS, "1");
			m.put(ApplicationUtils.MSG, "修改成功");
		} else {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "修改失败");
		}

		return m;
	}
	
	
	@Override
	public Map<String, Object> addUser(RequestUser user) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();
		
//		String user_id = ApplicationUtils.randomUUID();
//		user.setId(user_id);
//		User s = new User();
		
		if (StringUtils.isBlank(user.getC_role_id())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "角色不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getMember_name())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "家庭称谓不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getReal_name())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "真名不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getSex_code())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "性别不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getBirthday())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "生日不可为空");
			return m;
		}
		
		if (ApplicationUtils.isNotNull(user.getPhone())) {
			if (SpUtil.validatePhone(user.getPhone())) {
//						s.setPhone(user.getPhone());
//				s.setUsername(user.getPhone());
//				s.setPhone(user.getPhone());
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入正确的手机号");
				return m;
			}
		} else {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入手机号");
			return m;
		}
		
		List<Map<String,Object>> listp = this.ssoMapper.selectByPhone(user);
		if ((ApplicationUtils.isNotNull(listp)) && (listp.size() > 0)) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "该手机号已被注册");
			return m;
		}
		
		
		HashMap<String,Object> family=new HashMap<String,Object> ();
		String c_familyID=ApplicationUtils.randomUUID();
		family.put("family_name", user.getPhone()+"用户家庭");
		family.put("wx_point", 0);
		family.put("id", c_familyID);
		
		
		user.setC_family_id(c_familyID);
		String user_id = ApplicationUtils.randomUUID();
		user.setUser_id(user_id);//小孩的账号
		user.setUserName(ApplicationUtils.randomUUID());
		user.setPassword("123456");
		//设置以手机号为用户名的家长账号
		RequestUser fatherUser = new RequestUser();
		fatherUser.setUser_id(ApplicationUtils.randomUUID());
		fatherUser.setReal_name(user.getPhone()+"用户");
		fatherUser.setUserName(user.getPhone());
		fatherUser.setMember_name(user.getPhone()+"用户");
		fatherUser.setPassword("123456");
		fatherUser.setPhone(user.getPhone());
		fatherUser.setC_family_id(c_familyID);
		
		HashMap<String, Object> h1=new HashMap<String, Object>();
		int count=ssoMapper.getUserCountByPhone(h1);
		
		if(count>0){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "手机号重复");
			return m;
		}else{
			int effect=ssoMapper.insertFamily(family);
			if(effect==1){
				//小孩用户
				user.setPhone("");
				int effect2=ssoMapper.insertUser(user);
				//家长用户
				int effect3=ssoMapper.insertUser(fatherUser);
				if(effect2!=1||effect3!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "用户生成失败");
					return m;
				}
			}else{
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "插入家庭失败");
				return m;
			}
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		
		if("1".equalsIgnoreCase(user.getType())){
			//插入CRM关系表
			HashMap<String,Object> parm=Maps.newHashMap();
			parm.put("note",user.getAdmission_note());
	    	parm.put("customAssistID",user.getT_user_id());
	    	parm.put("customAssistName",user.getT_username());
			parm.put("cUserID", user_id);
			parm.put("phone", user.getPhone());
			parm.put("roleID", user.getC_role_id());
			parm.put("userName", user.getReal_name());
			int cnum=reprotMapper.checkCustomAssistCount(parm);
			if(cnum>0){
				reprotMapper.updateCustomAssist(parm);
			}else{
				reprotMapper.insertCustomAssist(parm);
			}
		}
		return m;
	}

	
	@Override
	public Map<String, Object> addUsers(RequestUser user) throws Exception{
		Map<String, Object> m = new HashMap<String, Object>();
		
//		String user_id = ApplicationUtils.randomUUID();
//		user.setId(user_id);
//		User s = new User();
		
		if (StringUtils.isBlank(user.getC_role_id())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "角色不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getMember_name())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "家庭称谓不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getReal_name())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "真名不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getSex_code())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "性别不可为空");
			return m;
		}
		
		if (StringUtils.isBlank(user.getBirthday())) {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "生日不可为空");
			return m;
		}
		
		if (ApplicationUtils.isNotNull(user.getPhone())) {
			if (SpUtil.validatePhone(user.getPhone())) {
//						s.setPhone(user.getPhone());
//				s.setUsername(user.getPhone());
//				s.setPhone(user.getPhone());
			} else {
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "请输入正确的手机号");
				return m;
			}
		} else {
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "请输入手机号");
			return m;
		}
		
		List<Map<String,Object>> listp = this.ssoMapper.selectByPhone(user);
		if ((ApplicationUtils.isNotNull(listp)) && (listp.size() > 0)) {
			m.put(ApplicationUtils.STATUS, "2");
			m.put(ApplicationUtils.MSG, "该手机号已被注册");
			return m;
		}
		
		
		HashMap<String,Object> family=new HashMap<String,Object> ();
		String c_familyID=ApplicationUtils.randomUUID();
		family.put("family_name", user.getPhone()+"用户家庭");
		family.put("wx_point", 0);
		family.put("id", c_familyID);
		
		
		user.setC_family_id(c_familyID);
		String user_id = ApplicationUtils.randomUUID();
		user.setUser_id(user_id);//小孩的账号
		user.setUserName(ApplicationUtils.randomUUID());
		user.setPassword("123456");
		//设置以手机号为用户名的家长账号
		RequestUser fatherUser = new RequestUser();
		fatherUser.setUser_id(ApplicationUtils.randomUUID());
		fatherUser.setReal_name(user.getParentName());
		fatherUser.setUserName(user.getPhone());
		fatherUser.setMember_name(user.getMember_name());
		fatherUser.setPassword("123456");
		fatherUser.setPhone(user.getPhone());
		fatherUser.setC_family_id(c_familyID);
		
		HashMap<String, Object> h1=new HashMap<String, Object>();
		int count=ssoMapper.getUserCountByPhone(h1);
		
		if(count>0){
			m.put(ApplicationUtils.STATUS, "0");
			m.put(ApplicationUtils.MSG, "手机号重复");
			return m;
		}else{
			int effect=ssoMapper.insertFamily(family);
			if(effect==1){
				//小孩用户
				user.setPhone("");
				int effect2=ssoMapper.insertUser(user);
				//家长用户
				int effect3=ssoMapper.insertUser(fatherUser);
				if(effect2!=1||effect3!=1){
					m.put(ApplicationUtils.STATUS, "0");
					m.put(ApplicationUtils.MSG, "用户生成失败");
					return m;
				}
			}else{
				m.put(ApplicationUtils.STATUS, "0");
				m.put(ApplicationUtils.MSG, "插入家庭失败");
				return m;
			}
		}
		
		m.put(ApplicationUtils.STATUS, "1");
		m.put(ApplicationUtils.MSG, "插入成功");
		
		if("1".equalsIgnoreCase(user.getType())){
			//插入CRM关系表
			HashMap<String,Object> parm=Maps.newHashMap();
			parm.put("note",user.getAdmission_note());
	    	parm.put("customAssistID",user.getT_user_id());
	    	parm.put("customAssistName",user.getT_username());
			parm.put("cUserID", user_id);
			parm.put("phone", user.getPhone());
			parm.put("roleID", user.getC_role_id());
			parm.put("userName", user.getReal_name());
			int cnum=reprotMapper.checkCustomAssistCount(parm);
			if(cnum>0){
				reprotMapper.updateCustomAssist(parm);
			}else{
				reprotMapper.insertCustomAssist(parm);
			}
		}
		return m;
	}


	@Override
	public List<HashMap<String,Object>> getRoleList() throws Exception{
		Map<String, Object> m = new HashMap();
		m.put("c_role_id", "0");
		List<HashMap<String,Object>> list=ssoMapper.getRoleList();
	//	List<HashMap> hm = consumeBackgroundMapper.getProductList(hmp);		
		
		return list;
	}

	@Override
	public List<HashMap<String, Object>> income() {
		return reprotMapper.income();
	}

	@Override
	public List<HashMap<String, Object>> cost() {
		return reprotMapper.cost();
	}

	@Override
	public BaseResult totalData() throws Exception {
		BaseResult br=null;
		
		BigDecimal yearIncome = reprotMapper.yearIncome();
		BigDecimal yearPayment = reprotMapper.yearPayment();
		BigDecimal yearContractIncome = reprotMapper.yearContractIncome();
		int yearContractCount = reprotMapper.yearContractCount();
		int yearNewUserCount = ssoMapper.yearNewUserCount();
		
		Map<String,Object> data=new HashMap<String,Object>();
		data.put("yearIncome", yearIncome);
		data.put("yearPayment", yearPayment);
		data.put("yearContractIncome", yearContractIncome);
		data.put("yearContractCount", yearContractCount);
		data.put("yearNewUserCount", yearNewUserCount);
		
		return new BaseResult("1","查询成功",data);		
	}
	
	@Override
	public List<HashMap<String, Object>> personIncome() {
		return reprotMapper.personIncome();
	}
	
	@Override
	public List<HashMap<String, Object>> personPayment() {
		return reprotMapper.personPayment();
	}	
	
	
	
}
